package com.jackchong.utils;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * author  : chong.huang
 * time    : 2021/8/16 17:39
 * desc    :
 */
public class JItemDecoration extends RecyclerView.ItemDecoration {

    private final int ml, mt, mr, mb, dividerV, dividerH;

    public JItemDecoration(int ml, int mt, int mr, int mb, int dividerV, int dividerH) {
        this.ml = ml;
        this.mt = mt;
        this.mr = mr;
        this.mb = mb;
        this.dividerV = dividerV;
        this.dividerH = dividerH;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        int lastPosition = -1;
        if (parent.getAdapter() != null && parent.getAdapter().getItemCount() > 0){
            lastPosition = parent.getAdapter().getItemCount();
        }
        int spanCount = 1;
        int orientation = RecyclerView.VERTICAL;
        if (parent.getLayoutManager() instanceof GridLayoutManager) {
            spanCount = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount();
            orientation = ((GridLayoutManager) parent.getLayoutManager()).getOrientation();
        }else if (parent.getLayoutManager() instanceof LinearLayoutManager) {
            orientation = ((LinearLayoutManager) parent.getLayoutManager()).getOrientation();
        }
        int position = parent.getChildAdapterPosition(view);

        if (orientation == RecyclerView.VERTICAL) {
            if (position % spanCount == 0){
                outRect.left = ml;
            }
            if (position % spanCount == spanCount - 1){
                outRect.right = mr;
            }
            if (position < spanCount) {
                outRect.top = mt;
            }
            if (position > lastPosition - spanCount + (position % spanCount)) {
                outRect.bottom = mb;
            }
            if (outRect.bottom == 0) {
                outRect.bottom = dividerV;
            }
            if (outRect.right == 0) {
                outRect.right = dividerH;
            }
        }else {
            if (position < spanCount) {
                outRect.left = ml;
            }
            if (position > lastPosition - spanCount + (position % spanCount)) {
                outRect.right = mr;
            }
            if (position % spanCount == 0){
                outRect.top = mt;
            }
            if (position % spanCount == spanCount - 1){
                outRect.bottom = mb;
            }
            if (outRect.bottom == 0) {
                outRect.bottom = dividerV;
            }
            if (outRect.right == 0) {
                outRect.right = dividerH;
            }
        }

    }
}


